package com.hr.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hr.dto.Page;
import com.hr.entity.Role;
import com.hr.entity.RoleMenu;
import com.hr.mapper.RoleMapper;
import com.hr.mapper.RoleMenuMapper;
import com.hr.service.RoleService;
import com.hr.vo.AuthVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Transactional
@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Override
    public void addRole(Role role) {
        roleMapper.addRole(role);
    }

    @Override
    public void deleteRole(Integer roleId) {
        roleMapper.deleteRole(roleId);
    }

    @Override
    public void updateRole(Role role) {
        roleMapper.updateRole(role);
    }

    @Override
    public Role getRole(Integer roleId) {
        return roleMapper.getRole(roleId);
    }

    @Override
    public Page getRolePage(int pageNo, int pageSize) {
        Page page = new Page();
        PageHelper.startPage(pageNo, pageSize);
        List<Role> roleList = roleMapper.getRoleList();
        PageInfo<Role> info = new PageInfo<>(roleList);
        page.setPageNo(info.getPageNum());
        page.setPageSize(info.getPageSize());
        page.setPageCount(info.getPages());
        page.setTotal(info.getTotal());
        page.setHasPrePage(info.isHasPreviousPage());
        page.setHasNextPage(info.isHasNextPage());
        page.setPage(info.getList());
        return page;
    }

    @Override
    public List<Role> getAllRole() {
        List<Role> roleList = roleMapper.getRoleList();
        roleList = roleList.stream().filter(el->el.getStatus()==1).collect(Collectors.toList());
        return roleList;
    }

    @Override
    public void auth(AuthVO authVO) {
        roleMenuMapper.deleteRoleMenuByRoleId(authVO.getRoleId());
        List<Integer> menuIds = authVO.getMenuIds();
        if(!CollectionUtils.isEmpty(menuIds)){
            for (Integer menuId : menuIds) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(authVO.getRoleId());
                roleMenu.setMenuId(menuId);
                roleMenu.setStatus(1);
                roleMenuMapper.addRoleMenu(roleMenu);
            }
        }
    }
}
